package com.tony.seavice;


import com.alibaba.fastjson.JSON;
import com.tony.entity.Content;
import com.tony.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService {


    @Autowired
    private RestHighLevelClient client;

    public List<Map<String,Object>> search(String keyword, Integer pageNum, Integer pageSize) {

        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from((pageNum-1)*pageSize+1);
        searchSourceBuilder.size(pageSize);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        //一个搜索结果只高亮第一个匹配 的
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);

        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        request.source(searchSourceBuilder);
        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        System.out.println(JSON.toJSONString(search.getHits()));
        if(search==null){
            return null;
        }
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields:search.getHits().getHits()){
//            System.out.println(documentFields.getSourceAsString());
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("title");
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            if(name!=null){
                Text[] fragments = name.fragments();
                String newName ="";
                for(Text t:fragments){
                    newName +=t;

                }
                sourceAsMap.put("title",newName);
                list.add(sourceAsMap);
            }
        }

        return list;
    }

    public boolean loadData(String keyword) {
        List<Content> contents = HtmlParseUtil.parseJD(keyword);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        try {
            GetIndexRequest requ = new GetIndexRequest("jd_goods");
            boolean exists = client.indices().exists(requ, RequestOptions.DEFAULT);
            if(!exists){
                CreateIndexRequest request = new CreateIndexRequest("jd_goods");
                CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        try {
            BulkResponse bulk1 = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk1.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
